package rs.mbs2.epics.server.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name="tag")
@NamedQueries ({
	@NamedQuery(name = "findTagByText",
			query="SELECT t FROM Tag t WHERE t.text LIKE :tagText"),
			
	@NamedQuery(name = "findTagsOnPhoto",
			query="SELECT t FROM Tag t LEFT JOIN t.taggedPhotos p WHERE p.id LIKE :photoId")
})
public class Tag implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "tag_id", unique = true, nullable = false)
	private Integer id;
	
	@Column(name = "tag_text", unique = false, nullable = false)
	private String  text;
	
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable( name = "tagged_photos",
				joinColumns = { @JoinColumn(name = "tag_id") },
				inverseJoinColumns = { @JoinColumn(name = "photo_id", referencedColumnName = "photo_id", nullable = false) })
	private Set<Photo> taggedPhotos;
	
	
	public Tag() {
		
	}

	public Tag(String text) {
		
		super();
		this.text = text;
		this.taggedPhotos = new HashSet<>();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Tag other = (Tag) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Set<Photo> getTaggedPhotos() {
		return taggedPhotos;
	}

	public void setTaggedPhotos(Set<Photo> taggedPhotos) {
		this.taggedPhotos = taggedPhotos;
	}

}
